import React, { useState, useEffect } from 'react';

export function UseTime(second) {
  const [lastTime, setLasttime] = useState(second);
  const [status, setStatus] = useState({
    start: false,
    suspend: false,
    cancel: false,
  });
  let timer = null;

  const isStart = () => {
    setStatus((val) => {
      return { ...val, start: true, suspend: false, cancel: false };
    });
  };
  const isSuspend = () => {
    setStatus((val) => {
      return { ...val, start: false, suspend: true, cancel: false };
    });
  };
  const isCancel = () => {
    setStatus((val) => {
      return { ...val, start: false, suspend: false, cancel: true };
    });
  };
  const isTimer = () => {
    timer = setTimeout(() => {
      setLasttime(lastTime - 1);
    }, 1000);
  };
  useEffect(() => {
    if (status.start) {
      isTimer();
    }
    if (status.suspend) {
      timer = null;
    }
    if (status.cancel || lastTime === 0) {
      clearTimeout(timer);
    }

    return () => {
      clearTimeout(timer);
    };
  }, [lastTime, status]);
  let fuc = {
    //开始
    isStart: isStart,
    //暂停
    isSuspend: isSuspend,
    //结束
    isCancel: isCancel,
    //结束的返回时间
    lastTime: lastTime,
  };
  return fuc;
}
